package common

import (
	"context"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc/metadata"
	"models/dal/model"
	"models/dal/query"
	"strconv"
	"time"
	"wrong"
)

// GetUserByHttp 获取http请求的用户
func GetUserByHttp(ctx *gin.Context) (*model.FaUser, error) {
	if userId, ok := ctx.Get("USER_ID"); ok {
		ctx, cancel := WithTimeoutContext(time.Second * 2)
		defer cancel()
		raw, err := query.Q.FaUser.WithContext(ctx).Where(query.Q.FaUser.ID.Eq(userId.(int32))).First()
		if err != nil {
			return nil, wrong.USER_NOT_FOUND
		}
		return raw, nil
	}
	return nil, wrong.NO_AUTH
}

// GetGinUserId 获取gin http的用户id
func GetGinUserId(ctx *gin.Context) (any, bool) {
	return ctx.Get("USER_ID")
}

// GetGrpcUserId 获取grpc metadata里的userid
func GetGrpcUserId(ctx context.Context) (int32, bool) {
	md, ok := metadata.FromIncomingContext(ctx)
	if ok {
		userIds := md.Get("user_id")
		if len(userIds) > 0 {
			userId, err := strconv.Atoi(userIds[0])
			if err != nil {
				return 0, false
			}
			return int32(userId), ok
		}
		return 0, false
	}
	return 0, false
}

// GetUserByGrpc 获取grpc里的用户
func GetUserByGrpc(ctx context.Context) (*model.FaUser, error) {
	userId, ok := GetGrpcUserId(ctx)
	if ok {
		timeoutCtx, cancel := WithTimeoutContext(time.Second * 2)
		defer cancel()
		raw, err := query.Q.FaUser.WithContext(timeoutCtx).Where(query.Q.FaUser.ID.Eq(userId)).First()
		if err != nil {
			return nil, wrong.USER_NOT_FOUND
		}
		return raw, nil
	}
	return nil, wrong.NO_AUTH
}

// GetUserVip 获取用户vip等级
func GetUserVip(raw *model.FaUser) int32 {
	vip := raw.Vip
	if raw.Vip > 0 {
		//是否过期
		if time.Now().After(raw.VipExpired) {
			vip = 0
		}
	}
	return vip
}
